package com.easy.nacos.consumer.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Packge com.easy.nacos.consumer.controller
 * @Autor linNaibin
 * @Description
 * @Version 1.0
 * @Date 2021/3/3 17:28
 */
@RestController
@ResponseBody
@RequestMapping("/")
public class ConsumerController {

    private final RestTemplate restTemplate;

    @Autowired
    public ConsumerController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * DiscoveryClient是Spring cloud提供的一个接口，可以用它来查询服务注册信息
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/get")
    @ResponseBody
    public String get() throws NacosException {
        // provider
        String serviceName = "provider";
        // DEFAULT_GROUP
        // 列出所有服务id
        List<String> services = discoveryClient.getServices();
        services.forEach(System.out::println);
        // 根据服务id获取实例
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
        return serviceName;
    }

    // 测试远程调用
    @GetMapping("/test")
    public String test() {

        try {
            return restTemplate.getForObject("http://provider/nacos/hello", String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            System.out.println("出错啦？！");
        }
        return "出错啦";

    }


}
